package com.icbc.user.interceptor;

import com.icbc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc token 拦截器
 */
@Component
public class JwtFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token信息
        String authorization = request.getHeader("Authorization");

        if(authorization!=null){
            if(authorization.startsWith("Bearer ")){
                String tonken = authorization.substring(7);

                Claims claims = jwtUtil.parseJWT(tonken);

                if(claims!=null){
                    if("admin".equals(claims.get("roles"))){
                        request.setAttribute("admin_claims",claims);
                    }else if("user".equals(claims.get("roles"))){
                        request.setAttribute("user_claims",claims);
                    }
                }

            }
        }

        return true;
    }
}
